package org.phantom.securityframework.auth.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.config.Ini;
import org.apache.shiro.realm.AuthorizingRealm;
import org.phantom.securityframework.api.SecurityManager;
import org.phantom.securityframework.api.ShiroConfigAware;
import org.phantom.securityframework.api.factory.ManagerFactory;
/**
 * 认证/鉴权基础父类
 * @author david
 *
 */
public abstract class DefaultAuthRealm extends AuthorizingRealm implements SubjectAuthRealm,ShiroConfigAware {

	private Ini ini;
	
	/**
	 * 设置CacheManager，子类重写覆盖TokenClass
	 */
	public DefaultAuthRealm() {
		this.setCacheManager(this.getCacheManager());
	}
	@Override
	public CacheManager getCacheManager() {
		return new MemoryConstrainedCacheManager(); 
	}
	
	/**
	 * 获取当前环境的Realm Factory
	 * @return
	 */
	protected ManagerFactory buildManagerFactory(){
		return ((SecurityManager)SecurityUtils.getSecurityManager()).getManagerFactory(this.ini);
	}

	public void setConfig(Ini ini) {
		this.ini = ini;
	}
	protected Ini getConfig(){
		return this.ini;
	}


	/**
	 * 获取当前环境AccountRealm
	 * @param factory
	 * @return
	 * @throws Exception
	 */
	public SubjectRealm buildSubjectRealm(ManagerFactory factory) throws Exception{
		if(factory==null){
			factory = this.buildManagerFactory();
		}
		return (SubjectRealm) factory.getService(SubjectRealm.class);
	}

	/**
	 * 获取当前环境SubjectPermissionRealms
	 * @param factory
	 * @return org.phantom.securityframework.auth.realm.SubjectPermissionRealm
	 * @throws Exception
	 */
	public SubjectPermissionRealm[] buildSubjectPermissionRealms(ManagerFactory factory) throws Exception{
		List<Object> subjectPermissionRealms =  factory.getServices(SubjectPermissionRealm.class);
		return subjectPermissionRealms.toArray(new SubjectPermissionRealm[subjectPermissionRealms.size()]);
	}
}
